package ynu.edu.elmservlet.service.impl;

import ynu.edu.elmservlet.dao.CartDao;
import ynu.edu.elmservlet.dao.OrderDetailetDao;
import ynu.edu.elmservlet.dao.OrdersDao;
import ynu.edu.elmservlet.dao.impl.CartDaoImpl;
import ynu.edu.elmservlet.dao.impl.OrderDetailetDaoImpl;
import ynu.edu.elmservlet.dao.impl.OrdersDaoImpl;
import ynu.edu.elmservlet.po.Cart;
import ynu.edu.elmservlet.po.OrderDetailet;
import ynu.edu.elmservlet.po.Orders;
import ynu.edu.elmservlet.service.OrdersService;
import ynu.edu.elmservlet.util.DBUtil;

import java.util.ArrayList;
import java.util.List;
public class OrdersServiceImpl implements OrdersService{
    @Override
    public int saveOrders(Orders orders) throws Exception {
        int orderId = 0;
        
        CartDao cartDao = new CartDaoImpl();
        OrdersDao ordersDao = new OrdersDaoImpl();
        OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
        
        try {
            DBUtil.beginTransaction(); // 开启事务
            
            // 1、查询当前用户购物车中当前商家的所有食品
            Cart cart = new Cart();
            cart.setUserId(orders.getUserId());
            cart.setBusinessId(orders.getBusinessId());
            List<Cart> cartList = cartDao.listCart(cart);
            
            if (cartList == null || cartList.isEmpty()) {
                System.out.println("Cart is empty for user: " + orders.getUserId());
                return 0;
            }
            
            // 2、创建订单，并获取订单编号
            orderId = ordersDao.saveOrders(orders);
            System.out.println("Created order with ID: " + orderId);
            
            if (orderId > 0) {
                // 3、向订单明细表中批量添加明细数据
                List<OrderDetailet> orderDetailetList = new ArrayList<>();
                for (Cart c : cartList) {
                    if (c.getFoodId() != null && c.getQuantity() != null) {
                        OrderDetailet od = new OrderDetailet();
                        od.setOrderId(orderId);
                        od.setFoodId(c.getFoodId());
                        od.setQuantity(c.getQuantity());
                        orderDetailetList.add(od);
                    }
                }
                
                if (!orderDetailetList.isEmpty()) {
                    int detailResult = orderDetailetDao.saveOrderDetailetBatch(orderDetailetList);
                    System.out.println("Saved " + detailResult + " order details");
                    
                    // 4、清空购物车（条件：当前用户、当前商家）
                    int cartResult = cartDao.removeCart(cart);
                    System.out.println("Removed " + cartResult + " items from cart");
                }
            }
            
            DBUtil.commitTransaction(); // 提交事务
            System.out.println("Order created successfully: " + orderId);
            
        } catch (Exception e) {
            orderId = 0;
            System.out.println("Create order error: " + e.getMessage());
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction(); // 回滚事务
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } finally {
            DBUtil.close(); // 关闭连接
        }
        
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) throws Exception {
        Orders orders = null;
        
        OrdersDao ordersDao = new OrdersDaoImpl();
        OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
        
        try {
            DBUtil.getConnection();  // 获取连接
            
            // 1、根据订单ID查询订单信息（包含商家信息）
            orders = ordersDao.getOrdersById(orderId);
            
            if (orders != null) {
                // 2、根据订单ID查询订单明细信息（包含食品信息）
                List<OrderDetailet> orderDetailetList = orderDetailetDao.listOrderDetailetByOrderId(orderId);
                orders.setOrderDetailetList(orderDetailetList);  // 使用正确的方法名
                
                // 打印调试信息
                System.out.println("Order ID: " + orders.getOrderId());
                System.out.println("Business: " + orders.getBusiness());
                System.out.println("Order Details Size: " + (orderDetailetList != null ? orderDetailetList.size() : 0));
                if (orderDetailetList != null) {
                    for (OrderDetailet detail : orderDetailetList) {
                        System.out.println("Detail: " + detail.getFoodId() + ", Food: " + detail.getFood());
                    }
                }
            }
            
        } finally {
            DBUtil.close();  // 关闭连接
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) throws Exception {
        List<Orders> list = new ArrayList<>();
        
        OrdersDao ordersDao = new OrdersDaoImpl();
        OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
        
        try {
            DBUtil.getConnection();
            
            // 1、根据用户ID查询订单信息（多对一：商家）
            list = ordersDao.listOrdersByUserId(userId);
            
            // 2、查询多个订单的订单明细信息
            for(Orders o : list) {
                List<OrderDetailet> odList = orderDetailetDao.listOrderDetailetByOrderId(o.getOrderId());
                o.setOrderDetailetList(odList);  // 修改这里
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }
}